package com.jd.user.service.impl;

import com.jd.basic.exception.BusinessException;
import com.jd.basic.service.impl.BaseServiceImpl;
import com.jd.basic.util.MD5Utils;
import com.jd.basic.util.StrUtils;
import com.jd.user.domain.Logininfo;
import com.jd.user.domain.User;
import com.jd.user.dto.UserDto;
import com.jd.user.mapper.LogininfoMapper;
import com.jd.user.mapper.UserMapper;
import com.jd.user.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private UserMapper userMapper;



    // 手机注册
    @Override
    public void phoneRegister(UserDto userDto) {
        String phone = userDto.getPhone();
        String phoneCode = userDto.getPhoneCode();
        String pwd = userDto.getPwd();
        String rePwd = userDto.getRePwd();
        // 1.校验 -空值校验
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(phoneCode)
           || StringUtils.isEmpty(pwd)|| StringUtils.isEmpty(rePwd)){
                throw new BusinessException("信息不能够为空");
        }

        // 2.校验 -密码是否相同
        if (!pwd.equals(rePwd)){
            throw new BusinessException("二次密码不一样");
        }

        // 3.校验 -短信验证码是否过期或者是否正确
        Object codeObj = redisTemplate.opsForValue().get("register:" + phone);
        if (codeObj==null){
            throw new BusinessException("手机验证码已经过期了");
        }
        if (!codeObj.toString().split(":")[0].equals(phoneCode)){
            throw new BusinessException("手机验证码错误");
        }


        // 4.添加到数据库
        User user = userDto2User(userDto);
        Logininfo logininfo = user2Logininfo(user);

        logininfoMapper.save(logininfo);

        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);


    }

    // 邮箱登录
    @Override
    public void emailRegister(UserDto userDto) {

            String email = userDto.getEmail();
            String rePwd = userDto.getRePwd();
            String pwd = userDto.getPwd();
            // 判断是否为空
            if(StringUtils.isEmpty(email) || StringUtils.isEmpty(pwd) || StringUtils.isEmpty(rePwd)) {
                throw new BusinessException("注册信息不能为空");
            }
            // 密码与确认密码是否一致
            if (!pwd.equals(rePwd)) {
                throw new BusinessException("密码不一致，请重新输入");

            }
            // 判断邮箱是否被注册
            User u = userMapper.loadByEmail(email);
            System.out.println(u);
            if (u != null) {
                throw new BusinessException("邮箱已注册，请前往登录");
            }
            // 保存到数据库
            Logininfo logininfo = new Logininfo();
            User user = new User();
            // 将密码加盐加密
            String salt = StrUtils.getComplexRandomString(32);
            String md5 = MD5Utils.encrypByMd5(userDto.getPwd() + salt);
            user.setPassword(md5);
            user.setEmail(email);
            user.setSalt(salt);
            user.setUsername(email);
            user.setState(1);

            // 将logininfo的id赋给user对象的logininfo属性
            BeanUtils.copyProperties(user,logininfo);
            logininfo.setType(1);
            logininfo.setDisable(false);
            logininfoMapper.save(logininfo);
            user.setLogininfoId(logininfo.getId());
            userMapper.save(user);

        }


    private User userDto2User(UserDto userDto) {
        User user = new User();
        user.setUsername(userDto.getPhone());
        user.setPhone(userDto.getPhone());
        String salt = StrUtils.getComplexRandomString(32);
        // 密码要加密加盐
        String md5Pwd = MD5Utils.encrypByMd5(userDto.getPwd() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        user.setState(1);

        return user;
    }


    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        // 按照属性同名原则
        BeanUtils.copyProperties(user,logininfo);
        // 用户
        logininfo.setType(1);
        logininfo.setDisable(true);

        return logininfo;

    }


    @Override
    @Transactional
    public void save(User user) {
        // 处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = MD5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);

        // 保存logininfo
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        logininfoMapper.save(logininfo);


        user.setLogininfoId(logininfo.getId());
        super.save(user); // 保存user
    }

    @Override
    @Transactional
    public void update(User user) {
        // 处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = MD5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        super.update(user);

        // 获取登录信息id
        Long logininfoId = userMapper.loadById(user.getId()).getLogininfoId();

        // 创建logininfo
        Logininfo logininfo = logininfoMapper.loadById(logininfoId);
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setId(logininfoId);
        logininfoMapper.update(logininfo);


    }

    @Override
    @Transactional
    public void remove(Long id) {

        // 删除登录信息
        User user = userMapper.loadById(id);
        logininfoMapper.remove(user.getLogininfoId());

        // 删除user信息
        super.remove(id);

    }










}
